package com.bitdf.txing.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bitdf.txing.chat.constant.Constant;
import com.bitdf.txing.chat.dao.ChatMessageDao;
import com.bitdf.txing.chat.entity.ChatMessageEntity;
import com.bitdf.txing.chat.service.ChatMessageService;
import com.bitdf.txing.chat.service.RedisService;
import com.bitdf.txing.common.utils.PageUtils;
import com.bitdf.txing.common.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("chatMessageService")
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageDao, ChatMessageEntity> implements ChatMessageService {

    @Autowired
    RedisService redisService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        IPage<ChatMessageEntity> page = this.page(
//                new Query<ChatMessageEntity>().getPage(params),
//                new QueryWrapper<ChatMessageEntity>()
//        );
//
//        return new PageUtils(page);
        return null;
    }

    /**
     * 获取私聊聊天记录 15条
     *
     * @param l
     * @param friendsList
     * @return
     */
    @Override
    public Map<Long, List<ChatMessageEntity>> getLastestChatMessageHistory(long l, List<UserInfoVo> friendsList) {
        if (friendsList == null || friendsList.size() == 0) {
            return null;
        }
        Map<Long, List<ChatMessageEntity>> hashMap = new HashMap<>();
        for (UserInfoVo userTo : friendsList) {
            long min = Math.min(l, userTo.getId());
            long max = Math.max(l, userTo.getId());
            String chatKey = Constant.CHATMESSAGE_SINGLE + max + "-" + min;
            List<ChatMessageEntity> list = redisService.getHistoryMessage(chatKey);
            hashMap.put(userTo.getId(), list);
        }
        return hashMap;
    }

    /**
     * 根据所传参数 获取 私聊/群聊 聊天记录
     *
     * @param sid
     * @param fid
     * @param lastTimeStamp
     * @param count
     * @return
     */
    @Override
    public List<ChatMessageEntity> getChatMessageHistory(Long sid, Long fid, Long lastTimeStamp, Integer count, String type) {
        Date lastDate = new Date(lastTimeStamp);
        // 获取要操作的redisKey
        String chatKey = null;
        Long min = 0L;
        Long max = 0L;
        if (type.equals("single")) {
            //先到redis中查询
            min = Math.min(sid, fid);
            max = Math.max(sid, fid);
            chatKey = Constant.CHATMESSAGE_SINGLE + max + "-" + min;
        } else {
            chatKey = Constant.CHATMESSAGE_GROUP + fid;
        }
        // 获取该用户对在redis中的所有聊天记录
        List<ChatMessageEntity> list = redisService.getRedisAllHistoryMessage(chatKey);
        //            new Date(1970, 01, 01, 0, 0, 0);
        if (list.get(list.size() - 1).getCreateTime().compareTo(lastDate) < 0) {
            // 说明现在要返回的聊天记录redis中还有
            List<ChatMessageEntity> collect = list.stream().filter((item) -> {
                return item.getCreateTime().compareTo(lastDate) < 0;
            }).limit(count).collect(Collectors.toList());
            return collect;
        }
        // redis中已查完 查数据库
        QueryWrapper<ChatMessageEntity> last;
        if (type.equals("single")) {
            // 单聊
            last = new QueryWrapper<ChatMessageEntity>().and(query -> {
                        query.eq("from_user_id", sid).eq("to_target_id", fid).or((query1) -> {
                            query1.eq("from_user_id", fid).eq("to_target_id", sid);
                        });
                    })
                    .and((query) -> {
                        query.lt("create_time", lastDate).eq("type", 0);
                    })
                    .orderByDesc("create_time").last(" limit " + count);
        } else {
            // 群聊
            last = new QueryWrapper<ChatMessageEntity>().and(query -> {
                        query.eq("to_target_id", fid);
                    })
                    .and((query) -> {
                        query.lt("create_time", lastDate).eq("type", 1);
                    })
                    .orderByDesc("create_time").last(" limit " + count);
        }
        // 查询
        List<ChatMessageEntity> list1 = this.list(last);
        return list1;
    }

    /**
     * 获取群聊聊天记录 15条
     *
     * @param keySet
     * @return
     */
    @Override
    public Map<Long, List<ChatMessageEntity>> getLastestGroupChatMessageHistory(Set<Long> keySet) {
        Map<Long, List<ChatMessageEntity>> hashMap = new HashMap<>();
        for (Long groupId : keySet) {
            String chatKey = Constant.CHATMESSAGE_GROUP + groupId;
            List<ChatMessageEntity> list = redisService.getGroupHistoryMessage(chatKey);
            hashMap.put(groupId, list);
        }
        return hashMap;
    }

}